package com.xiaokan.servlet;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xiaokan.datastructures.URLDictionary;
import com.xiaokan.pojo.URLWrapper;
import com.xiaokan.query.QueryProcessor;
import com.xiaokan.utils.DataManager;
import com.xiaokan.utils.MyProperties;

public class QueryServlet extends HttpServlet {

	private QueryProcessor qp = QueryProcessor.getInstance();
	private DataManager dm = DataManager.getInstance();
	private URLDictionary uDict = dm.readURLDict();
	private RandomAccessFile raf;
	private Pattern p = Pattern.compile(MyProperties.PATTERN_SPLIT);
	private int MAX_SNIPPETS = 5;

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		if (raf == null) {
			raf = new RandomAccessFile(MyProperties.SNIPPETS_FILE, "r");
		}
		String query = req.getParameter("query");
		String terms[] = p.split(query);
		URLWrapper results[] = qp.query(query, MyProperties.MAX_NUMBER_OF_SEARCH_RESULTS);
		if (results.length > 0) {
			String snippets[] = new String[MyProperties.MAX_NUMBER_OF_SEARCH_RESULTS];
			for (int i = 0; i < results.length; i++) {
				long start = results[i].getUrl().getStartFrom();
				long end = results[i].getUrl().getEndwith();
				byte buf[] = new byte[(int) (end - start)];
				raf.seek(start);
				raf.read(buf);
				String str = new String(buf);
				StringBuilder sb = new StringBuilder("...");
				for (String s : terms) {
					int j = str.indexOf(s);
					if (j == -1)
						continue;
					int l = j - 2, r = j + s.length() + 1;
					int numberOfLeft = 0, numberOfRight = 0;
					while (l >= 0 && numberOfLeft < MAX_SNIPPETS) {
						if (str.charAt(l) == ' ')
							numberOfLeft++;
						l++;
					}
					while (r < str.length() && numberOfRight < MAX_SNIPPETS) {
						if (str.charAt(r) == ' ')
							numberOfRight++;
						r++;
					}
					if (l < 0)
						l = 0;
					if (r >= str.length())
						r = str.length() - 1;
					if (l + 1 <= j)
						sb.append(str.substring(l + 1, j));
					sb.append("<b>");
					sb.append(str.substring(j, j + s.length()));
					sb.append("</b>");
					if (j + s.length() <= r)
						sb.append(str.substring(j + s.length(), r));
					sb.append("...");
				}
				snippets[i] = sb.toString();
				sb = null;
				str = null;
				buf = null;
			}
			req.setAttribute("res", results);
			req.setAttribute("snp", snippets);
		}
		req.getRequestDispatcher("index.jsp").forward(req, resp);
	}
}
